package com.smarttiger.zero.logic;

import com.smarttiger.zero.admin.dao.ArgsDao;
import com.smarttiger.zero.admin.dao.DataSourceDao;
import com.smarttiger.zero.admin.entity.DataSourceModel;
import com.smarttiger.zero.admin.entity.LogicModel;
import com.smarttiger.zero.admin.util.SpringContextUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Optional;


public class ExecuteLogics {

    public static Object executeLogics(List<LogicModel> logicModels) throws ClassNotFoundException {

        for (LogicModel e : logicModels) {
            String className = e.getClassName();
            Class aClass = Class.forName(className);
            BaseLogic logic = ((BaseLogic) SpringContextUtils.getBean(aClass));
            ArgsDao argsDao = SpringContextUtils.getBean(ArgsDao.class);
            logic.setArgsModels(argsDao.findAllByLogicId(e.getId()));
            if(!StringUtils.isEmpty(e.getDataSourceId())){
                DataSourceDao dataSourceDao = SpringContextUtils.getBean(DataSourceDao.class);
                Optional<DataSourceModel> dataSourceModel = dataSourceDao.findById(e.getDataSourceId());
                logic.setDataSourceModel(dataSourceModel.get());
            }
            logic.logic();
            Map<String, String> controll = InterfaceContext.logicControlContext.get();
            if(controll != null){
                if(controll.containsKey(InterfaceContext.CONTROLL_ERROR)){
                    break;
                }
                if(controll.containsKey(InterfaceContext.CONTROLL_BREAK)){
                    break;
                }
            }
        }
        Object o = InterfaceContext.resultContext.get();
        return o;
    }

}
